<?php namespace App\Controllers\Admin;
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 18-9-19
 * Time: 上午10:27
 */

use \App\Controllers\Application;


class Announce extends Application {

    protected $announce;

    public function __construct(...$params) {
        parent::__construct(...$params);

        if (!$this->user) {
            $this->showError("用户尚未登录，请登录后重新打开。", site_url(''));
        }
        $this->announce=new \App\Models\AnnounceModel();
    }

    public function index() {
        $this->data['announces']=$this->announce->orderBy('date','DESC')->findAll(5,0);
        $this->data['allAnnounce']=ceil($this->announce->countAll()/5);

        $this->render('admin/announce/list', '公告管理');
    }

    public function page() {
        $page = $this->request->getGet("page")>0?$this->request->getGet("page")-1:0;
        $this->data['announces']=$this->announce->orderBy('date','DESC')->findAll(5,5*$page);
        $this->render('admin/announce/page');
    }

    public function add($id=0) {
        if ($id) {
            $this->data['announce']=$this->announce->find($id);
        }
        $this->render('admin/announce/add');
    }

    public function save() {
        $content = $this->request->getPost("content");
        $content =preg_replace('/(style=".+")\ssrc/','src',$content);
        $announce=[
            'id' => $this->request->getPost("id")?:0,
            'title' => $this->request->getPost("title"),
            'content' => $content
        ];

        $this->announce->save($announce);
        $this->showJson("保存公告成功","Success");
    }

    public function delete($id) {
        if (!$id) {
            $this->showJson("没有选定要删除的公告","Error");
            return;
        }

        $this->announce->delete($id);
        $this->showJson("删除公告成功","Success");
    }
}